package com.leenmvc.core.config.filter;

import com.leenmvc.core.dao.communal.TransactionManager;
import com.leenmvc.core.utils.http.RequestParameterWrapper;
import com.leenmvc.core.utils.thread.ThreadLocalManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 在线程头部设置初始值
 */
@WebFilter(filterName = "headerFilter", urlPatterns = "/*")
public class ThreadHeadFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(ThreadHeadFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        try {
            if(!TransactionManager.transExist()) {
                ThreadLocalManager.setRequest((HttpServletRequest) request);
            }
            chain.doFilter(request, response);

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (ServletException e) {
            logger.error(e.getMessage(), e);
        }
        return;
    }

    private RequestParameterWrapper getRequestParameterWrapper(HttpServletRequest httpRequest, String path) {
        Map<String, Object> otherParams = new HashMap<>();
        otherParams.put("url", path);
        RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(httpRequest);
        requestParameterWrapper.addParameters(otherParams);
        return requestParameterWrapper;
    }

    @Override
    public void destroy() {
    }
}